package com.example.service

import com.example.data.dbQuery
import com.example.data.entity.HistoryEntity
import com.example.data.model.History
import com.example.tSimpleDateFormat
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq

class HistoryService {
    suspend fun getHistory(username: String, page: Int, pageSize: Int): List<History> {
        return dbQuery {
            HistoryEntity.select { HistoryEntity.username eq username }.orderBy(HistoryEntity.date to SortOrder.DESC)
                .limit(pageSize, (pageSize * (page - 1)).toLong()).map {
                    History(
                        it[HistoryEntity.id],
                        it[HistoryEntity.asmrId],
                        tSimpleDateFormat.format(it[HistoryEntity.date]),
                        it[HistoryEntity.img],
                        it[HistoryEntity.title],
                        it[HistoryEntity.username]
                    )
                }
        }
    }

    suspend fun add(history: History) = dbQuery {
        val b: Boolean
        val u = history.username!!
        if (HistoryEntity.selectAll()
                .where { (HistoryEntity.username eq u) and (HistoryEntity.asmrId eq history.asmrId) }.count() > 0
        ) {
            b = HistoryEntity.update({ (HistoryEntity.username eq u) and (HistoryEntity.asmrId eq history.asmrId) }) {
                it[date] = System.currentTimeMillis()
            } > 0
        } else {
            b = HistoryEntity.insert {
                it[asmrId] = history.asmrId
                it[date] = System.currentTimeMillis()
                if (history.img != null) it[img] = history.img
                if (history.title != null) it[title] = history.title
                it[username] = u
            }.insertedCount > 0
        }
        b
    }

    suspend fun delete(id: Int) = dbQuery { HistoryEntity.deleteWhere { HistoryEntity.id eq id } > 0 }

    suspend fun clear(u: String) = dbQuery {
        HistoryEntity.deleteWhere {
            username eq u
        } > 0
    }
}